<script setup>
import {
  ArrowRight,
  Clock,
  UploadFilled,
  User,
} from "@element-plus/icons-vue";
import {getShareFolder, ownLink, parseUrl, parseUser, urlExist} from "@/apis/share";
import {formatBytes} from "@/utils/ByteUtil";
import {onMounted, ref} from "vue";
import fileIcon from "@/images/icon/file.png";
import videoIcon from "@/images/icon/video.png";
import audioIcon from "@/images/icon/audio.png";
import zipIcon from "@/images/icon/zip.png";
import javaIcon from "@/images/icon/java.png";
import javascriptIcon from "@/images/icon/javascript.png";
import exeIcon from "@/images/icon/exe.png";
import pdfIcon from "@/images/icon/pdf.png";
import docIcon from "@/images/icon/doc.png";
import pptIcon from "@/images/icon/ppt.png";
import xlsIcon from "@/images/icon/xls.png";
import txtIcon from "@/images/icon/txt.png";
import rtfIcon from "@/images/icon/rtf.png";
import csvIcon from "@/images/icon/csv.png";
import htmlIcon from "@/images/icon/html.png";
import xmlIcon from "@/images/icon/xml.png";
import nullIcon from "@/images/icon/null.png";
import {ElMessage} from "element-plus";
import {serverPath} from "@/utils/path";
import {saveShare} from "@/apis/user";
import {logout} from "@/apis/login";
import router from "@/router";


const href = window.location.href;
const remove = "/#/share"
const split = "?url="
const s = href.substring(href.indexOf(remove) + remove.length + split.length);
const show = ref(true)
const shareList = ref([])
const status = ref(false)
const input = ref("")
const user = ref({
  name: "",
  avatar: "",
  createTime: "",
  expiryTime: ""
})
const downloadStatus = ref(true)
const selectFiles = ref([])
const navigationBar = ref([])
const saveCloudDisk = ref(true)
const saveButtonStatus = ref(true)
const downloadButtonStatus = ref(true)
onMounted(()=>{

  ownLink(s).then(res => {
    if (res.data.data === true){
      getFileInfo()
      saveCloudDisk.value = false
    }
  })
})

function saveFiles() {
  if(saveButtonStatus.value === false){
    ElMessage({
      type:"warning",
      message:"你的操作太快了"
    })
    return
  }

  if (selectFiles.value.length <= 0) {
    ElMessage({
      type:"warning",
      message:"还没有选择任何文件"
    })
    return
  }

  saveButtonStatus.value = false
  const fileIds = []
  for (let i = 0; i < selectFiles.value.length; i++) {
    fileIds.push(selectFiles.value[i].id)
  }
  saveShare(fileIds).then(res => {
    if(res.data.code === 200){
      ElMessage({
        type:"success",
        message:res.data.data
      })
    }
  })

  setTimeout(() =>{
    saveButtonStatus.value = true
  },1500)

}

function imagePreview(row) {
  const fileName = row.fileName
  const fileId = row.fileId;
  // 如果是图片类型
  const image = ["jpg", "jpeg", "png", "gif", "bmp", "webp"]
  const video = ["mp4", "avi", "mkv", "mov", "wmv", "flv", "mpeg", "webm", "3gp"]
  const audio = ["mp3", "wav", "ogg", "flac", "aac", "wma", "m4a", "opus", "mid", "midi", "amr", "ac3", "ape"]
  const documentation = ["pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "txt", "rtf", "csv", "html", "xml"]
  const zip = ["zip", "rar", "7z", "tar", "gz", "bz2"];
  if (row.folderType === 0) {
    return fileIcon
  } else if (image.some(ext => fileName.toLowerCase().endsWith(ext))) {
    return `${serverPath}/preview/thumbnail/${fileId}`
  } else if (video.some(ext => fileName.toLowerCase().endsWith(ext))) {
    return videoIcon
  } else if (audio.some(ext => fileName.toLowerCase().endsWith(ext))) {
    return audioIcon
  } else if (zip.some(ext => fileName.toLowerCase().endsWith(ext))) {
    return zipIcon
  } else if (fileName.toLowerCase().endsWith("java") || fileName.toLowerCase().endsWith("jar")) {
    return javaIcon
  } else if (fileName.toLowerCase().endsWith("javascript")) {
    return javascriptIcon
  } else if (fileName.toLowerCase().endsWith("exe")) {
    return exeIcon
  } else if (documentation.some(ext => fileName.toLowerCase().endsWith(ext))) {
    if (fileName.toLowerCase().endsWith("pdf")) {
      return pdfIcon
    } else if (fileName.toLowerCase().endsWith("doc") || fileName.toLowerCase().endsWith("docx")) {
      return docIcon
    } else if (fileName.toLowerCase().endsWith("ppt") || fileName.toLowerCase().endsWith("pptx")) {
      return pptIcon
    } else if (fileName.toLowerCase().endsWith("xls") || fileName.toLowerCase().endsWith("xlsx")) {
      return xlsIcon
    } else if (fileName.toLowerCase().endsWith("txt")) {
      return txtIcon
    } else if (fileName.toLowerCase().endsWith("rtf")) {
      return rtfIcon
    } else if (fileName.toLowerCase().endsWith("csv")) {
      return csvIcon
    } else if (fileName.toLowerCase().endsWith("html")) {
      return htmlIcon
    } else if (fileName.toLowerCase().endsWith("xml")) {
      return xmlIcon
    }
  } else {
    return nullIcon
  }
  // return `http://192.168.151.78:80/preview/thumbnail/${fileId}`
}

function begin() {
  parseUrl(s, input.value).then(res => {
    status.value = true
    shareList.value = res.data.data
    navigationBar.value = [];
  })
}

function getFileInfo() {
  urlExist(s).then(res => {
    if (res.data.data === false) {
      show.value = false
    } else {
      parseUrl(s, input.value).then(res => {
        if (res.data.code === 200) {
          status.value = true
          shareList.value = res.data.data

          parseUser(s).then(res => {
            user.value.name = res.data.data.name
            user.value.avatar = res.data.data.avatar
            user.value.createTime = res.data.data.createTime
            user.value.expiryTime = res.data.data.expiryTime
          })
        }
      })
    }
  })
}

function date(timestamp) {
  const time = new Date(timestamp).getTime();
// 创建一个 Date 对象，将时间戳传递给构造函数
  const date = new Date(time);

// 使用 Date 对象的方法获取各个时间部分
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 注意月份从 0 开始
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();

// 将获取到的时间部分拼接成指定格式
  return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")} ${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
}

function selectFile(selection) {
  selectFiles.value = selection
  downloadStatus.value = true
  for (let i = 0; i < selectFiles.value.length; i++) {
    if (selectFiles.value[i].folderType === 0) {
      downloadStatus.value = false
      break
    }
  }
}

function clickNavigationBar(item) {
  // 如果点击的是最后一个就不做任何事情
  if (item.fileId === navigationBar.value[navigationBar.value.length - 1].fileId) {
    return
  }

  let newNavigationBar = []
  for (let i = 0; i < navigationBar.value.length; i++) {
    if (item.fileId === navigationBar.value[i].fileId) {
      newNavigationBar.push(navigationBar.value[i])
      break
    }
    newNavigationBar.push(navigationBar.value[i])
  }
  navigationBar.value = newNavigationBar
  getFolderInfo(item.fileId)
}

async function getFolder(row) {
  if (row.folderType === 0) {
    getFolderInfo(row.id)
    navigationBar.value.push({
      name: row.fileName,
      fileId: row.id
    })
  } else {
    // TODO 分享文件处预览 (暂时不做 有空补上 没空就算了)
  }

}

async function getFolderInfo(id) {
  const res = await getShareFolder(id)
  shareList.value = res.data.data
}

async function downloadList() {
  if(saveButtonStatus.value === false){
    ElMessage({
      type:"warning",
      message:"你的操作太快了"
    })
    return
  }

  if (selectFiles.value.length <= 0) {
    ElMessage({
      type:"warning",
      message:"还没有选择任何文件"
    })
    return
  }

  if (downloadStatus.value === false) {
    ElMessage.error('不能下载文件夹')
    return
  }

  downloadButtonStatus.value = false

  let minioName = []
  let fileName = []
  for (let i = 0; i < selectFiles.value.length; i++) {
    minioName.push(selectFiles.value[i].minioName)
    fileName.push(selectFiles.value[i].fileName)
  }

  // 下载文件
  const downloadLink = document.createElement('a');
  downloadLink.href = `${serverPath}/file/downloadList/${minioName}/${fileName}`
  downloadLink.click();

  setTimeout(() => {
    downloadButtonStatus.value = true
  },1500)
}

const dropdown = ref(null)
function userClick(){
  dropdown.value.handleOpen()
}
function clickLogout(){
  logout()
}
</script>

<template>
  <div class="all" style="height: 100%">
    <div class="share-header">
      <!--左边log-->
      <div class="header-left">
        <div class="header-icon-div">
          <el-icon class="header-icon" style="color: deepskyblue" size="40">
            <UploadFilled/>
          </el-icon>
        </div>
        <div class="header-icon-div"><span class="header-text">Simple云盘</span></div>
      </div>
      <!--右边内容-->
      <div class="header-right">
        <!-- 用户信息 -->
        <div class="right2">
          <el-dropdown ref="dropdown" trigger="contextmenu" style="margin-right: 30px">
            <el-icon @click="userClick" size="20" class="smallHands">
              <el-image :src="serverPath + '/user/getAvatar'"></el-image>
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="clickLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

        </div>
      </div>
    </div>
    <!--内容-->
    <div v-if="status" class="share-body">
      <!--整体-->
      <div v-if="show" class="share-body-content" style="height: 660px">
        <!--头部-->
        <div style="margin-top: 10px;margin-left: 12px;display: flex">
          <div>
            <el-button v-if="saveCloudDisk" style="border: 1px solid #c3eaff;"><span style="font-size: 10px;color: #09aaff" @click="saveFiles" >保存到网盘</span></el-button>
            <el-button @click="downloadList" style="border: 1px solid #c3eaff;"><span
                style="font-size: 10px;color: #09aaff">下载</span></el-button>
          </div>
          <div style="display: flex;justify-content: flex-end;margin-left: auto;margin-right: 30px">
            <span style="margin-left: 15px">{{ user.name }}</span>
          </div>

        </div>
        <!--时间-->
        <div style="margin-top: 15px; margin-left: 12px; display: flex; align-items: center;">
          <div style="margin-right: 3px">
            <el-icon style="display: flex; align-items: center;">
              <Clock/>
            </el-icon>
          </div>
          <div style="display: flex;align-content: center;align-items: center">
            <span style="font-size: 12px; color: #666666;">{{ date(user.createTime) }}</span>
          </div>
          <div style="display: flex;align-content: center;align-items: center">
            <span
                style="font-size: 12px; color: #666666; margin-left: 15px;">过期时间: {{
                user.expiryTime === null ? "永久有效" : date(new Date(user.expiryTime))
              }}</span>
          </div>
        </div>
        <!--横线-->
        <div style="margin-top: 1px;margin-left: 12px;margin-right: 10px;height: 1px">
          <hr color="#f6f6f6">
        </div>
        <!--面包屑-->
        <div style="margin-top: 20px;margin-left: 20px;display: flex;align-items: center;align-content: center">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item @click="begin">
                  <span class="smallHands"
                        style="font-size: 10px;font-weight: bold;color: #6e6e6e;user-select: none;">
                    全部文件
                  </span>
            </el-breadcrumb-item>
            <el-breadcrumb-item v-for="item in navigationBar">
                  <span class="smallHands" @click="clickNavigationBar(item)"
                        style="font-size: 10px;font-weight: bold;color: #6e6e6e;user-select: none;">
                    {{ item.name }}
                  </span>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <!--表格-->
        <div class="table" style="margin-left: 12px;margin-right: 10px;margin-top: 10px">
          <el-table
              :data="shareList"
              ref="fileTable"
              style="width: 100%;"
              max-height=535
              @selection-change="selectFile"
          >
            <!--选择框-->
            <el-table-column type="selection" width="30"/>
            <!--文件名-->
            <el-table-column width="500" label="文件名">
              <template v-slot="scope">
                <div class="smallHands" style="display: flex">
                  <!-- 图片 -->
                  <div style="display: flex;align-items: center;align-content: center; margin-right: 12px;">
                    <img style="height: 30px;width: 30px;user-select: none;" :src="imagePreview(scope.row)">
                  </div>
                  <div @click="getFolder(scope.row)"
                       style="display: flex;align-items: center;width: 400px;align-content: center"
                       class="smallHands">
                        <span
                            style="font-size: 12px;font-weight: 600;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;user-select: none;">{{
                            scope.row.fileName
                          }}</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <!--操作按钮-->
            <el-table-column width="200">
            </el-table-column>
            <!--文件大小-->
            <el-table-column label="大小">
              <template v-slot="scope">
                {{ formatBytes(scope.row.fileSize) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div v-if="!show" class="share-body-content"
           style="height: 660px;display: flex;align-content: center;align-items: center;justify-content: center">
        <div>
          <span>文件不存在</span>
        </div>
      </div>
    </div>

    <div v-if="!status" class="share-body">
      <!--整体-->
      <div v-if="show" class="share-body-content"
           style="height: 660px;align-items: center;align-content: center;justify-content: center">
        <div style="margin-top: -200px;margin-bottom: 15px">
          <el-input v-model="input" placeholder="请输入提取码,区分大小写" style="width: 200px"/>
        </div>
        <div>
          <el-button type="primary" @click="getFileInfo" style="width: 200px">提取</el-button>
        </div>

      </div>
    </div>
  </div>

</template>

<style scoped lang="scss">

.share-body {
  display: flex;
  justify-content: center;
}

.header-right {
  display: flex;
  justify-content: flex-end;
  margin-left: auto;
  margin-right: 40px;
}

.right2 {
  margin-left: 20px;
}

.share-body-content {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  width: 96%;
  background-color: #fff;
  border: 1px solid #efefef;
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.2);
}

.share-header {
  width: 100%;
  display: flex;
  height: 50px;
  background-color: #fff;
  border-bottom: 1px solid #eeeeee;
  align-content: center;
  align-items: center;
  box-shadow: 0 0 10px #e3e3e3;
}

.smallHands{
  cursor: pointer;
}

.header-left {
  display: flex;
  margin-left: 20px;
  align-items: center;
  align-content: center;
}

.header-icon-div {
  margin: 0 5px;
}

.header-icon {
  color: #05a1f5;
}

.header-text {
  color: #05a1f5;
  font-size: 25px;
  font-weight: bold;
  align-content: center;
  align-items: center;
}
</style>